﻿import { useState } from "react"
import { useScreenshotState } from "../utils/hooks"

interface ScreenshotTabProps {
  onInsertToEditor: (imageSrc: string, altText: string) => void
}

export default function ScreenshotTab({ onInsertToEditor }: ScreenshotTabProps) {
  const [isCapturing, setIsCapturing] = useState(false)
  const [currentScreenshot, setCurrentScreenshot] = useState<string | null>(null)
  const [error, setError] = useState<string | null>(null)
  
  // 使用持久化状态管理截屏历史
  const {
    screenshots,
    isLoading: screenshotsLoading,
    saveScreenshot,
    deleteScreenshot,
    clearScreenshots
  } = useScreenshotState()

  // 截屏功能
  const captureScreen = async () => {
    try {
      setIsCapturing(true)
      setError(null)

      const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })
      
      if (!tab.id) {
        throw new Error("无法获取当前标签页")
      }

      const dataUrl = await chrome.tabs.captureVisibleTab(tab.windowId, {
        format: "png",
        quality: 100
      })

      setCurrentScreenshot(dataUrl)
      
      // 保存到持久化存储
      await saveScreenshot({
        id: Date.now().toString(),
        dataUrl,
        timestamp: Date.now(),
        name: `截屏_${new Date().toLocaleString()}`
      })
    } catch (err) {
      setError(err instanceof Error ? err.message : "截屏失败")
    } finally {
      setIsCapturing(false)
    }
  }

  const downloadScreenshot = (screenshot: string, name?: string) => {
    const link = document.createElement("a")
    link.download = name || `screenshot-${new Date().toISOString().slice(0, 19).replace(/:/g, "-")}.png`
    link.href = screenshot
    link.click()
  }

  const clearCurrentScreenshot = () => {
    setCurrentScreenshot(null)
    setError(null)
  }

  // 插入截屏到编辑器
  const insertScreenshotToEditor = (screenshot: string) => {
    onInsertToEditor(screenshot, "截屏图片")
  }

  return (
    <div>
      <h3 style={{ marginTop: 0, color: "#333" }}>
         截屏工具
      </h3>
      
      <div style={{ marginBottom: 16 }}>
        <button
          onClick={captureScreen}
          disabled={isCapturing}
          style={{
            width: "100%",
            padding: "12px",
            backgroundColor: isCapturing ? "#ccc" : "#007bff",
            color: "white",
            border: "none",
            borderRadius: "6px",
            fontSize: "14px",
            cursor: isCapturing ? "not-allowed" : "pointer",
            marginBottom: "8px"
          }}>
          {isCapturing ? "截屏中..." : " 截取当前页面"}
        </button>
      </div>

      {error && (
        <div
          style={{
            padding: "8px",
            backgroundColor: "#f8d7da",
            color: "#721c24",
            borderRadius: "4px",
            marginBottom: "12px",
            fontSize: "12px"
          }}>
           {error}
        </div>
      )}

      {/* 当前截屏预览 */}
      {currentScreenshot && (
        <div style={{ marginTop: 16, marginBottom: 16 }}>
          <div style={{ marginBottom: 8 }}>
            <img
              src={currentScreenshot}
              alt="当前截屏预览"
              style={{
                width: "100%",
                maxHeight: "150px",
                objectFit: "contain",
                border: "1px solid #ddd",
                borderRadius: "4px"
              }}
            />
          </div>
          
          <div style={{ display: "flex", gap: "8px", marginBottom: 8 }}>
            <button
              onClick={() => downloadScreenshot(currentScreenshot)}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#28a745",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               下载
            </button>
            
            <button
              onClick={() => insertScreenshotToEditor(currentScreenshot)}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#17a2b8",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               插入编辑器
            </button>
            
            <button
              onClick={clearCurrentScreenshot}
              style={{
                flex: 1,
                padding: "8px",
                backgroundColor: "#6c757d",
                color: "white",
                border: "none",
                borderRadius: "4px",
                fontSize: "12px",
                cursor: "pointer"
              }}>
               清除
            </button>
          </div>
        </div>
      )}

      {/* 截屏历史 */}
      {screenshots.length > 0 && (
        <div style={{ marginTop: 16 }}>
          <div style={{ 
            display: "flex", 
            justifyContent: "space-between", 
            alignItems: "center",
            marginBottom: 8 
          }}>
            <h4 style={{ margin: 0, fontSize: "14px", color: "#333" }}>
               截屏历史 ({screenshots.length})
            </h4>
            <button
              onClick={clearScreenshots}
              style={{
                padding: "4px 8px",
                backgroundColor: "#dc3545",
                color: "white",
                border: "none",
                borderRadius: "3px",
                fontSize: "11px",
                cursor: "pointer"
              }}>
               清空历史
            </button>
          </div>
          
          <div style={{ 
            maxHeight: "200px", 
            overflowY: "auto",
            border: "1px solid #ddd",
            borderRadius: "4px",
            padding: "8px"
          }}>
            {screenshots.map((screenshot) => (
              <div
                key={screenshot.id}
                style={{
                  display: "flex",
                  alignItems: "center",
                  padding: "8px",
                  border: "1px solid #eee",
                  borderRadius: "4px",
                  marginBottom: "8px",
                  backgroundColor: "#f9f9f9"
                }}>
                <img
                  src={screenshot.dataUrl}
                  alt={screenshot.name || "截屏"}
                  style={{
                    width: "60px",
                    height: "40px",
                    objectFit: "cover",
                    borderRadius: "3px",
                    marginRight: "8px"
                  }}
                />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ 
                    fontSize: "12px", 
                    fontWeight: "bold",
                    color: "#333",
                    marginBottom: "2px",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap"
                  }}>
                    {screenshot.name || "未命名截屏"}
                  </div>
                  <div style={{ 
                    fontSize: "10px", 
                    color: "#666" 
                  }}>
                    {new Date(screenshot.timestamp).toLocaleString()}
                  </div>
                </div>
                <div style={{ display: "flex", gap: "4px" }}>
                  <button
                    onClick={() => insertScreenshotToEditor(screenshot.dataUrl)}
                    style={{
                      padding: "4px 6px",
                      backgroundColor: "#17a2b8",
                      color: "white",
                      border: "none",
                      borderRadius: "3px",
                      fontSize: "10px",
                      cursor: "pointer"
                    }}
                    title="插入到编辑器">
                    
                  </button>
                  <button
                    onClick={() => downloadScreenshot(screenshot.dataUrl, screenshot.name)}
                    style={{
                      padding: "4px 6px",
                      backgroundColor: "#28a745",
                      color: "white",
                      border: "none",
                      borderRadius: "3px",
                      fontSize: "10px",
                      cursor: "pointer"
                    }}
                    title="下载">
                    
                  </button>
                  <button
                    onClick={() => deleteScreenshot(screenshot.id)}
                    style={{
                      padding: "4px 6px",
                      backgroundColor: "#dc3545",
                      color: "white",
                      border: "none",
                      borderRadius: "3px",
                      fontSize: "10px",
                      cursor: "pointer"
                    }}
                    title="删除">
                    
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {screenshotsLoading && (
        <div style={{ 
          textAlign: "center", 
          padding: "20px",
          color: "#666",
          fontSize: "12px"
        }}>
           加载截屏历史中...
        </div>
      )}
    </div>
  )
}
